import { defineStore } from 'pinia'
import { ref } from 'vue'
import { mediaApi } from '@/api/modules/media'
import type { MediaFile, PaginationParams, PaginationResponse } from '@/types'

export const useMediaStore = defineStore('media', () => {
  const mediaFiles = ref<MediaFile[]>([])
  const currentMedia = ref<MediaFile | null>(null)
  const loading = ref(false)
  const pagination = ref({
    page: 1,
    pageSize: 12,
    total: 0
  })

  // 获取媒体文件列表
  const getMediaFiles = async (params?: Partial<PaginationParams>) => {
    loading.value = true
    try {
      const searchParams: PaginationParams = {
        page: pagination.value.page,
        pageSize: pagination.value.pageSize,
        ...params
      }
      
      const result = await mediaApi.getMediaFiles(searchParams)
      mediaFiles.value = result.list
      pagination.value.total = result.total
      pagination.value.page = result.page
      pagination.value.pageSize = result.pageSize
      
      return result
    } finally {
      loading.value = false
    }
  }

  // 获取单个媒体文件
  const getMediaFile = async (id: string) => {
    const media = await mediaApi.getMediaFile(id)
    if (media) {
      currentMedia.value = media
    }
    return media
  }

  // 删除媒体文件
  const deleteMediaFile = async (id: string) => {
    await mediaApi.deleteMediaFile(id)
    // 从列表中移除
    const index = mediaFiles.value.findIndex(file => file.id === id)
    if (index > -1) {
      mediaFiles.value.splice(index, 1)
      pagination.value.total--
    }
  }

  // 更新媒体文件
  const updateMediaFile = async (id: string, data: Partial<MediaFile>) => {
    const updatedMedia = await mediaApi.updateMediaFile(id, data)
    if (updatedMedia) {
      // 更新列表中的数据
      const index = mediaFiles.value.findIndex(file => file.id === id)
      if (index > -1) {
        mediaFiles.value[index] = updatedMedia
      }
      // 更新当前媒体
      if (currentMedia.value?.id === id) {
        currentMedia.value = updatedMedia
      }
    }
    return updatedMedia
  }

  // 设置分页参数
  const setPagination = (page: number, pageSize?: number) => {
    pagination.value.page = page
    if (pageSize) {
      pagination.value.pageSize = pageSize
    }
  }

  // 重置状态
  const reset = () => {
    mediaFiles.value = []
    currentMedia.value = null
    pagination.value = {
      page: 1,
      pageSize: 12,
      total: 0
    }
  }

  return {
    mediaFiles,
    currentMedia,
    loading,
    pagination,
    getMediaFiles,
    getMediaFile,
    deleteMediaFile,
    updateMediaFile,
    setPagination,
    reset
  }
}) 